import random
from django import forms
from django.core.validators import RegexValidator
from django.core.validators import RegexValidator, EmailValidator
from django.core.exceptions import ValidationError
from web import models
from web.utils.encrypt import encrypt

class LoginFormWithPW(forms.ModelForm):
    mobile_phone = forms.CharField(
        required=True,
        label='手机号',
        validators=[RegexValidator(regex=r'^(1[3|4|5|6|7|8|9])\d{9}$', message='手机号格式不正确'),],
        error_messages={
            'required': '手机号必须填'
        }
    )
    password = forms.CharField(
        required=True,
        label='密码',
        widget=forms.PasswordInput(),
        error_messages={
            'required': '密码必须填'
        },
        validators=[RegexValidator(regex=r'^(?![0-9a-zA-Z]+$)(?![0-9\W]+$)(?![a-zA-Z\W]+$)[0-9A-Za-z\W]{8,16}$', message='必须是8-16位包含字母、数字和符号的密码'),]
    )

    def __init__(self, request, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.request = request

    def clean_mobile_phone(self):
        mobile_phone = self.cleaned_data['mobile_phone']
        exists = models.User.objects.filter(mobile_phone=mobile_phone).exists()
        if not exists:
            raise ValidationError('手机号不存在')
        return mobile_phone

    def clean_password(self):
        password = self.cleaned_data['password']
        # 加密
        # password = encrypt(password)
        return password
    
    class Meta:
        model = models.User
        fields = ['mobile_phone', 'password']

class LoginFormWithCode(forms.ModelForm):
    mobile_phone = forms.CharField(
        required=True,
        label='手机号',
        validators=[RegexValidator(regex=r'^(1[3|4|5|6|7|8|9])\d{9}$', message='手机号格式不正确'),],
        error_messages={
            'required': '手机号必须填'
        }
    )
    code = forms.CharField(
        required=True,
        label='验证码',
        error_messages={
            'required': '请输入验证码'
        },
        widget=forms.TextInput()
    )

    def __init__(self, request, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.request = request

    def clean_mobile_phone(self):
        mobile_phone = self.cleaned_data['mobile_phone']
        exists = models.User.objects.filter(mobile_phone=mobile_phone).exists()
        if not exists:
            raise ValidationError('手机号不存在')
        return mobile_phone
    
    def clean_code(self):
        code = self.cleaned_data['code']
        # 验证验证码
        confirm_code = self.request.session.get('code', None)
        print(code, confirm_code)
        if confirm_code == 'None':
            # 失效
            raise ValidationError('验证码失效')
        elif str(code) != str(confirm_code):
            # 错误
            raise ValidationError('验证码错误')
        return code
    
    class Meta:
        model = models.User
        fields = ['mobile_phone', 'code']

class RegisterModelForm(forms.ModelForm):
    """ 注册表单"""

    # 手机号
    mobile_phone = forms.CharField(
        required=True,
        label='手机号',
        validators=[RegexValidator(regex=r'^(1[3|4|5|6|7|8|9])\d{9}$', message='手机号格式不正确'),],
        error_messages={
            'required': '手机号必须填'
        }
    )
    
    username = forms.CharField(
        required=True,
        label='用户名',
        widget=forms.TextInput(),
        error_messages={
            'required': '用户名必须填'
        }
    )
    
    email = forms.CharField(
        required=True,
        label='邮箱',
        widget=forms.TextInput(),
        error_messages={
            'required': '邮箱必须填'
        },
        validators=[EmailValidator(message='邮箱格式不正确'),]
    )

    password = forms.CharField(
        required=True,
        label='密码',
        widget=forms.PasswordInput(),
        error_messages={
            'required': '密码必须填'
        },
        validators=[RegexValidator(regex=r'^(?![0-9a-zA-Z]+$)(?![0-9\W]+$)(?![a-zA-Z\W]+$)[0-9A-Za-z\W]{8,16}$', message='必须是8-16位包含字母、数字和符号的密码'),]
    )

    confirm_password = forms.CharField(
        required=True,
        label='确认密码',
        error_messages={
            'required': '请确认密码'
        },
        widget=forms.PasswordInput()
    )

    code = forms.CharField(
        required=True,
        label='验证码',
        error_messages={
            'required': '请输入验证码'
        },
        widget=forms.TextInput()
    )

    def __init__(self, request, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.request = request
    
    def clean_code(self):
        code = self.cleaned_data['code']
        # 验证验证码
        confirm_code = self.request.session.get('code', None)
        print(code, confirm_code)
        if confirm_code == 'None':
            # 失效
            raise ValidationError('验证码失效')
        elif str(code) != str(confirm_code):
            # 错误
            raise ValidationError('验证码错误')
        return code
    
    def clean_confirm_password(self):
        password = self.cleaned_data.get('password', None)
        if password != None:
            confirm_password = self.cleaned_data['confirm_password']
            if password != confirm_password:
                raise ValidationError('密码与确认密码必须相同')
        else:
            raise ValidationError('请检查密码是否满足要求')
        return password
    
    def clean_mobile_phone(self):
        mobile_phone = self.cleaned_data['mobile_phone']

        # 手机号是否存在
        exists = models.User.objects.filter(mobile_phone=mobile_phone).exists()

        if exists:
            raise ValidationError('手机已存在')

        return mobile_phone
    
    def clean_password(self):
        password = self.cleaned_data['password']
        # 加密
        # password = encrypt(password)
        return password
    
    class Meta:
        model = models.User
        fields = ['username', 'email', 'password', 'confirm_password', 'mobile_phone', 'code']


class ModifyModelForm(forms.ModelForm):
    """ 注册表单"""

    # 手机号
    mobile_phone = forms.CharField(
        required=True,
        label='手机号',
        validators=[RegexValidator(regex=r'^(1[3|4|5|6|7|8|9])\d{9}$', message='手机号格式不正确'),],
        error_messages={
            'required': '手机号必须填'
        }
    )
    
    username = forms.CharField(
        required=True,
        label='用户名',
        widget=forms.TextInput(),
        error_messages={
            'required': '用户名必须填'
        }
    )
    
    email = forms.CharField(
        required=True,
        label='邮箱',
        widget=forms.TextInput(),
        error_messages={
            'required': '邮箱必须填'
        },
        validators=[EmailValidator(message='邮箱格式不正确'),]
    )

    password = forms.CharField(
        required=True,
        label='密码',
        widget=forms.PasswordInput(),
        error_messages={
            'required': '密码必须填'
        },
        validators=[RegexValidator(regex=r'^(?![0-9a-zA-Z]+$)(?![0-9\W]+$)(?![a-zA-Z\W]+$)[0-9A-Za-z\W]{8,16}$', message='必须是8-16位包含字母、数字和符号的密码'),]
    )

    confirm_password = forms.CharField(
        required=True,
        label='确认密码',
        error_messages={
            'required': '请确认密码'
        },
        widget=forms.PasswordInput()
    )

    code = forms.CharField(
        required=True,
        label='验证码',
        error_messages={
            'required': '请输入验证码'
        },
        widget=forms.TextInput()
    )

    def __init__(self, request, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.request = request
    
    def clean_code(self):
        code = self.cleaned_data['code']
        # 验证验证码
        confirm_code = self.request.session.get('code', None)
        print(code, confirm_code)
        if confirm_code == 'None':
            # 失效
            raise ValidationError('验证码失效')
        elif str(code) != str(confirm_code):
            # 错误
            raise ValidationError('验证码错误')
        return code
    
    def clean_confirm_password(self):
        password = self.cleaned_data.get('password', None)
        if password != None:
            confirm_password = self.cleaned_data['confirm_password']
            if password != confirm_password:
                raise ValidationError('密码与确认密码必须相同')
        else:
            raise ValidationError('请检查密码是否满足要求')
        return password
    
    def clean_password(self):
        password = self.cleaned_data['password']
        # 加密
        # password = encrypt(password)
        return password
    
    class Meta:
        model = models.User
        fields = ['username', 'email', 'password', 'confirm_password', 'mobile_phone', 'code']

    
# Create your views here.
class SendSmsForm(forms.Form):
    """发送短信表单验证"""
    # 手机号
    mobile_phone = forms.CharField(
        required=True,
        label='手机号',
        validators=[RegexValidator(regex=r'^(1[3|4|5|6|7|8|9])\d{9}$', message='手机号格式不正确'),],
        error_messages={
            'required': '手机号必须填'
        }
    )
    

    def __init__(self, request, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.request = request

    def clean_mobile_phone(self):
        mobile_phone = self.cleaned_data['mobile_phone']

        # 判断模版是否存在
        template = self.request.GET.get('template')
        
        # 生成验证码
        code = random.randrange(1000, 9999)
        print("验证码：" + str(code))
        # 存入session
        self.request.session['code'] = code
        self.request.session.set_expiry(60)

        return mobile_phone